package com.example.dell.startproject_224lx.model;

import com.example.dell.startproject_224lx.bean.WeatherResult;
import com.example.dell.startproject_224lx.iface.WeatherIface;
import com.example.dell.startproject_224lx.iface.WeatherListener;
import com.example.dell.startproject_224lx.service.WeatherService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by dell on 2017/4/6.
 */

public class WeatherModel implements WeatherIface {
    private Retrofit retrofit;
    private String BASEURL="http://www.weather.com.cn/";
    private WeatherService weatherService;

    public WeatherModel(Retrofit retrofit,String BASEURL){
        this.retrofit=retrofit;
        this.BASEURL=BASEURL;
    }
 public WeatherModel(){
     //Retrofit使用3-1
     retrofit=new Retrofit.Builder()
             .baseUrl(BASEURL)
             .addConverterFactory(GsonConverterFactory.create())
             .build();
 }
    @Override
    public void getWeather(String cityno, final WeatherListener listener){
        System.out.println("------WeatherModel--getWeather---------");
        //Retrofits使用3-2
        weatherService=retrofit.create(WeatherService.class);
       Call<WeatherResult>call=weatherService.getResult(cityno);
        //Retrofit使用3-3

        call.enqueue (new Callback<WeatherResult>() {
            public void onResponse(Call<WeatherResult> call, Response<WeatherResult> response) {
                if (response.isSuccessful() && response.body()!= null)
                    listener.onResponse(response.body().getWeatherinfo());
                else
                    listener.onFail("inresponse fail");

            }

            public void onFailure(Call<WeatherResult> call, Throwable t) {
                listener.onFail(t.toString());

            }
        });



    }
}
